package com.wing.cms.controller;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.wing.cms.domain.Channel;
import com.wing.cms.domain.Site;
import com.wing.cms.service.ArticleManager;
import com.wing.cms.service.ChannelManager;
import com.wing.cms.service.SiteManager;
import com.wing.common.Constants;
import com.wing.common.util.ApplicationPath;
import com.wing.common.util.FileUtils;
import com.wing.common.util.GUID;
import com.wing.common.util.PageBean;
import com.wing.sys.domain.Auth;
import com.wing.sys.domain.User;
import com.wing.sys.service.AuthManager;
import com.wing.sys.service.UserManager;

/**
 * 
 * 
 * @author  wyf
 * 
 */
 
@Controller
@RequestMapping(value = "/cms/site")
public class SiteController {

	@Autowired
	private SiteManager siteManager;
	@Autowired
	private AuthManager authManager;
	@Autowired
	private UserManager userManager;
	@Autowired
	private ArticleManager articleManager;
	@Autowired
	private ChannelManager channelManager;
	/**
	 * 获得列表数据
	 *  
	 */
	@RequestMapping(method = RequestMethod.GET)
	public String list() {
		return "/cms/site/siteIndex";
	}
	
	@RequestMapping(value = "get/{url}", method = RequestMethod.GET)
	public String get(@PathVariable String url) {
		return "cms/site/"+url;
	}
		
	@RequestMapping(value = "list", method = RequestMethod.POST)
	public @ResponseBody PageBean list(int currentPage, String pageSize,String seachv) {
		int _iPageSize = 0;
		if (pageSize == null) {
			_iPageSize =  PageBean.DEFAULT_PAGESIZE;
		} else {
			_iPageSize= Integer.parseInt(pageSize);
		}
		return  siteManager.findPageList(currentPage, _iPageSize,seachv);
	}
	
	
	@RequestMapping(value = "toForm/{id}",method = RequestMethod.GET)
	public String toForm(@PathVariable String id,Model model) {
		Site site = null;
		String sitemgrId = "";
		String sitemgrName = "";
		if(!id.equals("0")){
			site = siteManager.findById(id);
			List auths = authManager.getAuthsByTypeResId(Auth.TYPE_SITE, site.getId());
			if(auths.size()>0){
				sitemgrId = ((Auth)auths.get(0)).getOwner_id();
				User u = userManager.findById(sitemgrId);
				sitemgrName = u.getName();
			}
		}else{
			site = new Site();
		}
		model.addAttribute("site", site);
		model.addAttribute("sitemgrId", sitemgrId);
		model.addAttribute("sitemgrName", sitemgrName);
		return "/cms/site/siteForm";
	}
	
	@RequestMapping(value = "toAuth/{id}",method = RequestMethod.GET)
	public String toAuth(@PathVariable String id,HttpServletRequest request) {
		List list = authManager.getAuthsByTypeOwnerId(Auth.TYPE_LAYOUT,id);
		String authlayouts = "";
		for(int i=0;i<list.size();i++){
			Auth a = (Auth)list.get(i);
			authlayouts+=a.getRes_id()+",";
		}
		
		list = authManager.getAuthsByTypeOwnerId(Auth.TYPE_TEMPLATE,id);
		String authtemplates = "";
		for(int i=0;i<list.size();i++){
			Auth a = (Auth)list.get(i);
			authtemplates+=a.getRes_id()+",";
		}
		list = authManager.getAuthsByTypeOwnerId(Auth.TYPE_LOOKFEL,id);
		String authlookfeels = "";
		for(int i=0;i<list.size();i++){
			Auth a = (Auth)list.get(i);
			authlookfeels+=a.getRes_id()+",";
		}
		list = authManager.getAuthsByTypeOwnerId(Auth.TYPE_FUNCTION,id);
		String authfuns = "";
		for(int i=0;i<list.size();i++){
			Auth a = (Auth)list.get(i);
			authfuns+=a.getRes_id()+",";
		}
		request.setAttribute("authlayouts", authlayouts);
		request.setAttribute("authtemplates", authtemplates);
		request.setAttribute("authlookfeels", authlookfeels);
		request.setAttribute("authfuns", authfuns);
		request.setAttribute("siteId", id);
		return "/cms/site/authForm";
	}
	
	@RequestMapping(value = "auth",method = RequestMethod.POST)
	public @ResponseBody String auth(String siteId,String layIds,String tempIds,String lkIds,String funIds) {
		String[] lays = layIds.split(","); 
		authManager.updateAuthsByTypeOwnerId(Auth.TYPE_LAYOUT,siteId,lays);
		String[] temps = tempIds.split(","); 
		authManager.updateAuthsByTypeOwnerId(Auth.TYPE_TEMPLATE,siteId,temps);
		String[] kls = lkIds.split(","); 
		authManager.updateAuthsByTypeOwnerId(Auth.TYPE_LOOKFEL,siteId,kls);
		String[] funs = funIds.split(","); 
		authManager.updateAuthsByTypeOwnerId(Auth.TYPE_FUNCTION,siteId,funs);
		
		return Constants.DEFAULT_AJAX_SUCCESS;
	}
	
	@RequestMapping(value = "ajaxauth",method = RequestMethod.POST)
	public @ResponseBody String ajaxauth(String siteId,String type,String id,String state) {
		List list = authManager.getAuths(type,siteId,id);
		
		if(list.size()==0){
			if("true".equals(state)){
				Auth a = new Auth();
				a.setType(type);
				a.setOwner_id(siteId);
				a.setRes_id(id);
				a.setId(new GUID().toString());
				authManager.insert(a);
			}
			return Constants.DEFAULT_AJAX_SUCCESS;
		}
		if("false".equals(state)){
			for(int i=0;i<list.size();i++){
				authManager.deleteAuth((Auth)list.get(i));
			}
		}
		return Constants.DEFAULT_AJAX_SUCCESS;
	}
	
	@RequestMapping(value = "save", method = RequestMethod.POST)
	public @ResponseBody String save(Site site,String sitemgrId) {
		if(siteManager.checkSitePathRepeat(site.getId(),site.getSite_path())){
			return "domainrepeat";
		}
		siteManager.saveSite(site,sitemgrId);
		initUrlMap();
		return Constants.DEFAULT_AJAX_SUCCESS;
	}
	
	@RequestMapping(value = "delsites", method = RequestMethod.POST)
	public @ResponseBody String delsites(String[] chk) throws IOException {
		siteManager.deleteSites(chk);
		return ""+chk.length;
	}
	
	@RequestMapping(value = "getsites", method = RequestMethod.POST)
	public @ResponseBody List getsites(HttpServletRequest request) {
		String userId = (String)request.getSession().getAttribute(Constants.SESSION_USER_ID);
		List list =  siteManager.getSitesBySiteMgrs(userId);
		if(!Constants.SYSTEM_SUPERADMIN_ID.equals(userId)){
			//因为超级管理员会在上一步中获取所有的站点所以没必要再获取一次。
			list.addAll(siteManager.getSitesBySiteUser(userId));
		}
		return  list;
	}
	@RequestMapping(value = "changesite", method = RequestMethod.POST)
	public @ResponseBody String changesite(String siteId,String siteName,HttpServletRequest request) {
		request.getSession().setAttribute(Constants.SESSION_SITE_ID,siteId);
		request.getSession().setAttribute(Constants.SESSION_SITE_NAME,siteName);
		request.getSession().setAttribute(Constants.SESSION_SITE_PATH,siteManager.findById(siteId).getSite_path());
		return Constants.DEFAULT_AJAX_SUCCESS;
	}
	
	@RequestMapping(value = "toClone/{id}",method = RequestMethod.GET)
	public String toClone(@PathVariable String id,Model model) {
		Site site = null;
		if(!id.equals("0")){
			site = siteManager.findById(id);
		}else{
			site = new Site();
		}
		model.addAttribute("site", site);
		return "/cms/site/cloneForm";
	}
	@RequestMapping(value = "cloneSite", method = RequestMethod.POST)
	public @ResponseBody String cloneSite(String src_sitePath,
			String dest_sitePath,String dest_siteUrl,String siteName,String ownerUser) {
		dest_sitePath=dest_sitePath.toLowerCase();
		if(siteManager.checkSitePathRepeat(null,dest_sitePath)){
			return "domainrepeat";
		}
		Map<String, Object> oldSite = (Map<String, Object>) siteManager.getSitesBySitePath(src_sitePath).get(0);
		Integer clone_num = (Integer)oldSite.get("clone_num");
		int rodmomB=(int)(Math.random()*900)+100; 
		String rodmomCPId = "cp"+ clone_num.toString()+new Integer(rodmomB).toString()+"V";
		try {
			FileUtils.copyDirectory(ApplicationPath.getParameter("appRoot")+"/site/"+src_sitePath,ApplicationPath.getParameter("appRoot")+"/site/"+dest_sitePath,rodmomCPId);
		} catch (Exception e) {
			e.printStackTrace();
			return Constants.DEFAULT_AJAX_FAILURE;
		}
		siteManager.cloneSite(src_sitePath, dest_sitePath,dest_siteUrl, siteName, ownerUser,rodmomCPId);
		initUrlMap();
		return Constants.DEFAULT_AJAX_SUCCESS;
	}
	
	@RequestMapping(value = "yblcSite", method = RequestMethod.POST)
	public @ResponseBody Map yblcSite(String srcpath,String siteName
					,HttpServletRequest request,String login_code,String destpath,String desturl) {
		destpath=destpath.toLowerCase();
		Map map = new HashMap();
		String validateC = (String) request.getSession().getAttribute("validateCode");
		String veryCode = request.getParameter("veryCode");
		if(!validateC.equals(veryCode.toUpperCase())){ 
			map.put("status",Constants.DEFAULT_AJAX_FAILURE );
			map.put("code","veryCodeError" );
			return map;         
		} 
		String site_userId = (String)request.getSession().getAttribute(Constants.SESSION_SITE_USER_ID);
		
		if(site_userId==null){
			//雅宝路用户没有登录
			map.put("status",Constants.DEFAULT_AJAX_FAILURE );
			map.put("code","notlogin" );
			return map;
		}
		List list =userManager.findUsersByLoginCode(login_code);
		if(list.size()>0){
			List sites =  siteManager.getSitesBySiteMgrs((String)((Map)list.get(0)).get("id"));
			if(sites.size()>0){
				//该用户已经复制过一个站点
				map.put("status",Constants.DEFAULT_AJAX_FAILURE );
				map.put("code","exist" );
				return map;
			}
		}else{
			//创建用户 密码默认为111111	
			User u = new User();
			u.setCreatetime(new Date());
			u.setLogin_code(login_code);
			u.setPassword("111111");
			u.setName(login_code);
			userManager.saveUser(u,site_userId);	
		}
		if(siteManager.checkSitePathRepeat(null,destpath)){
			//路径已被使用
			map.put("status",Constants.DEFAULT_AJAX_FAILURE );
			map.put("code","domainrepeat" );
			return map;
		}
		
		//复制站点
		String src_sitePath = srcpath;
		String dest_sitePath = destpath;
		Map<String, Object> oldSite = (Map<String, Object>) siteManager.getSitesBySitePath(src_sitePath).get(0);
		Integer clone_num = (Integer)oldSite.get("clone_num");
		int rodmomB=(int)(Math.random()*900)+100; 
		String rodmomCPId = "cp"+ clone_num.toString()+new Integer(rodmomB).toString()+"V";
		try {
			FileUtils.copyDirectory(ApplicationPath.getParameter("appRoot")+"/site/"+src_sitePath,ApplicationPath.getParameter("appRoot")+"/site/"+dest_sitePath,rodmomCPId);
		} catch (Exception e) {
			e.printStackTrace();
			map.put("status",Constants.DEFAULT_AJAX_FAILURE );
			map.put("code","error" );
			return map;
		}
		siteManager.cloneSite(src_sitePath, dest_sitePath,destpath+desturl, siteName, site_userId,rodmomCPId);
		map.put("status",Constants.DEFAULT_AJAX_SUCCESS );
		map.put("login_code",login_code);
		map.put("password","111111");
		initUrlMap();
		return map;
	}
	
	@RequestMapping(value = "bakSite", method = RequestMethod.POST)
	public @ResponseBody String bakSite(String siteId) {
		siteManager.bakSite(siteId);
		return Constants.DEFAULT_AJAX_SUCCESS;
	}
	
	@RequestMapping(value = "indexSite", method = RequestMethod.POST)
	public @ResponseBody String indexSite(String siteId) {
		try {
			articleManager.indexSite(siteId);
		} catch (IOException e) {
			e.printStackTrace();
			return Constants.DEFAULT_AJAX_FAILURE;
		}
		return Constants.DEFAULT_AJAX_SUCCESS;
	}
	@RequestMapping(value = "getCpSites", method = RequestMethod.POST)
	public @ResponseBody PageBean getCpSites(int currentPage, String pageSize,String site) {
		int _iPageSize = 0;
		if (pageSize == null) {
			_iPageSize =  PageBean.DEFAULT_PAGESIZE;
		} else {
			_iPageSize= Integer.parseInt(pageSize);
		}
		return  siteManager.getCpSites(currentPage, _iPageSize,site);
	}
	

	private void initUrlMap(){
		Constants.urlMap = new HashMap();
		System.out.println("+++++++++++++++++++++++++init urlmap++"+new Date()+"++++++++++++++++++++++++");
		List list = siteManager.findAll();
		for(int i=0;i<list.size();i++){
			Map map = (Map)list.get(i);
			Constants.urlMap.put((String)map.get("site_url"), (String)map.get("site_path"));
			Constants.urlMap.put((String)map.get("site_url")+"_id", (String)map.get("id"));
			Constants.urlMap.put((String)map.get("site_url")+"_status", ((Integer)map.get("status")).toString());
			Constants.urlMap.put((String)map.get("site_url")+"_sitename", (String)map.get("site_name"));
			Constants.urlMap.put((String)map.get("site_url")+"_homeurl", getHomeUrl((String)map.get("site_url")));
		}
		Constants.urlMap.put("demo1.58ybl.com", "demo1");
		Constants.urlMap.put("demo1.58ybl.com_id", "0000000500130c066bb0");
		Constants.urlMap.put("demo1.58ybl.com_status", "0");
		Constants.urlMap.put("demo1.58ybl.com_sitename", "示例1");
		Constants.urlMap.put("demo1.58ybl.com_homeurl", getHomeUrl("demo1.58ybl.com"));
		
		Constants.urlMap.put("demo2.58ybl.com", "demo2");
		Constants.urlMap.put("demo2.58ybl.com_id", "000000031001312661ce70");
		Constants.urlMap.put("demo2.58ybl.com_status", "0");
		Constants.urlMap.put("demo2.58ybl.com_sitename", "示例2");
		Constants.urlMap.put("demo2.58ybl.com_homeurl", getHomeUrl("demo2.58ybl.com"));
		
		Constants.urlMap.put("demo3.58ybl.com", "demo3");
		Constants.urlMap.put("demo3.58ybl.com_id", "00000001001316a2cf533");
		Constants.urlMap.put("demo3.58ybl.com_status", "0");
		Constants.urlMap.put("demo3.58ybl.com_sitename", "示例3");
		Constants.urlMap.put("demo3.58ybl.com_homeurl", getHomeUrl("demo3.58ybl.com"));
		
		Constants.urlMap.put("58ybl.com", "ybl");
		Constants.urlMap.put("58ybl.com_id", "yblsite01");
		Constants.urlMap.put("58ybl.com_status", Site.SITE_STATUS_DIRECT);
		Constants.urlMap.put("58ybl.com_sitename", "雅宝网");
		Constants.urlMap.put("58ybl.com_homeurl", getHomeUrl("58ybl.com"));
		
		Constants.urlMap.put("wingcms.com", "qzw");
		Constants.urlMap.put("wingcms.com_id", "000000020012e664bc4c8");
		Constants.urlMap.put("wingcms.com_status", Site.SITE_STATUS_DIRECT);
		Constants.urlMap.put("wingcms.com_sitename", "企助网");
		Constants.urlMap.put("wingcms.com_homeurl", getHomeUrl("wingcms.com"));
		
		Constants.urlMap.put("127.0.0.1", "qzw");
		Constants.urlMap.put("127.0.0.1_id", "000000020012e664bc4c8");
		Constants.urlMap.put("127.0.0.1_status", Site.SITE_STATUS_DIRECT);
		Constants.urlMap.put("127.0.0.1_sitename", "企助网");
		Constants.urlMap.put("127.0.0.1_homeurl", getHomeUrl("127.0.0.1"));
	}
	private String getHomeUrl(String url){
		String sitepath=(String)Constants.urlMap.get(url);
		String status=(String)Constants.urlMap.get(url+"_status");
		if(Site.SITE_STATUS_DIRECT.equals(sitepath)){
			return "/site/"+sitepath+"/index.jsp";
		}else{
			List list = channelManager.findChannelsBySiteId( (String)Constants.urlMap.get(url+"_id"));
			String redircturl = "/site/"+sitepath+"/index.jsp";
			if(list.size()>0){
				Map map = (Map)list.get(0);
				Channel c = channelManager.findById((String)map.get("id"));
				if(c!=null && c.getIspub()==1){
					redircturl = "/site/"+sitepath+"/"+map.get("id")+".html";
				}else{
					redircturl = "/cms/channel/layout/"+map.get("id");
				}
			}
			//response.sendRedirect(redircturl);
			return redircturl;
		}
	}
}

